import React, { Component } from 'react';
import { Button,Dialog,Loading,Progress  } from 'qnui';
import { Row, Col } from 'qnui/lib/grid';
import CropperJS from 'react-cropperjs';
import ObjectAssign from 'object-assign';
import Mime from './mime.js';
export default class CropperUpload extends Component {
	constructor(props) {
		super(props);
		this.state = {
			loadding:<Loading color="#e6e6e6" size="large"/>,
			percent:0
			};
		['cropDone','onCropOkay','showLoading','hideLoading'].map(fn => {
            this[fn] = this[fn].bind(this);
        });
	}
	onCropOkay(){
		const dataUrl = this.refs.cropper.getCroppedCanvas({width:"750",height:"421"}).toDataURL();
		var decodeData = dataUrl.substring(dataUrl.indexOf('base64,') + 7);
		decodeData = atob(decodeData);
		this.post(decodeData, dataUrl);
	}
	showLoading(){
		this.setState({"loadding":<Loading color="#e6e6e6" size="large"/>});
	}
	hideLoading(){
		this.setState({"loadding":""});
	}
	cropDone(e){
		this.setState({"percent":0});
		// image in dataUrlgetCropBoxData
		// console.log(this.refs.cropper.getCropBoxData());
		// console.log(this.refs.cropper.getCroppedCanvas().toDataURL());
	}
	post(decodeData, dataUrl) {
		if(!decodeData){
			console.log("image data is empty！")
			return;
		}
        var _this3 = this;
        var _props2 = this.props,
            action = _props2.uploadServer,
            name = _props2.name,
            headers = _props2.headers,
            multipart = _props2.multipart,
            formatter = _props2.formatter,
            _onProgress = _props2.onProgress,
            _onSuccess = _props2.onSuccess,
            _onError = _props2.onError;
		let getBody = function(xhr) {
			var text = xhr.responseText || xhr.response;
			if (!text) {
				return text;
			}

			try {
				return JSON.parse(text);
			} catch (e) {
				return text;
			}
		}
		let send = function (xhr, data) {
			if (typeof data === 'string') {
				// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/sendAsBinary
				if (xhr.sendAsBinary) {
					// Gecko
					xhr.sendAsBinary(data);
				} else {
					// WebKit with typed arrays support
					var ui8a = new Uint8Array(data.length);
					for (var i = 0, l = data.length; i < l; i++) {
						ui8a[i] = data.charCodeAt(i) & 0xff;
					}
					xhr.send(ui8a.buffer);
				}
			} else {
				xhr.send(data);
			}
		}
		let upload = function(option){
			if (typeof XMLHttpRequest === 'undefined') {
				console.log("not supported enverioment");
				return;
			}

			var xhr = new XMLHttpRequest();
			if (xhr.upload) {
				xhr.upload.onprogress = function progress(e) {
					if (e.total > 0) {
						e.percent = e.loaded / e.total * 100;
					}
					option.onProgress(e);
				};
			}
			var formData = void 0;
			var fileName = option.file && option.file.name || '';
			var multipartArgs = (0, ObjectAssign)({
				name: fileName
			}, option.multipart);
			if (typeof option.bin === 'string') {
				(function () {
					var now = +new Date();
					let uid = (now++).toString(36); //生成唯一的id
					
					var bin = option.bin;
					var boundary = '----ksuploadboundary' + uid;
					var dashdash = '--';
					var crlf = '\r\n';
					var multipartBlob = '';
					option.headers = option.headers || {};

					// if no FormData we can still try to send it directly as last resort (see below)
					// Trying to send the whole thing as binary...

					// Added multipart request
					option.headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
					// append multipart parameters
					Object.keys(multipartArgs).forEach(function (name) {
						multipartBlob += dashdash + boundary + crlf + 'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf;
						multipartBlob += unescape(encodeURIComponent(multipartArgs[name])) + crlf;
					});

					var mimeType = Mime[option.file.name.replace(/^.+\.([^.]+)/, '$1').toLowerCase()] || 'application/octet-stream';

					// Build RFC2388 blob
					multipartBlob += dashdash + boundary + crlf + 'Content-Disposition: form-data; name="' + option.filename + '"; filename="' + unescape(encodeURIComponent(option.file.name)) + '"' + crlf + 'Content-Type: ' + mimeType + crlf + crlf + bin + crlf + dashdash + boundary + dashdash + crlf;

					// multipartDeltaSize = multipartBlob.length - bin.length;
					formData = multipartBlob;
				})();
			} else {
				formData = new FormData();

				Object.keys(multipartArgs).map(function (key) {
					option.multipart && formData.append(key, option.multipart[key]);
				});

				formData.append('name', fileName);
				formData.append(option.filename, option.bin);
			}
			xhr.onerror = function error(e) {
				option.onError(e);
			};

			xhr.onload = function onload() {
				if (xhr.status < 200 || xhr.status >= 300) {
					return option.onError(_this3.props.onUploadError(option, xhr), getBody(xhr));
				}
				option.onSuccess(getBody(xhr));
			};

			xhr.open('post', option.action, true);

			// Has to be after `.open()`. See https://github.com/enyo/dropzone/issues/179
			if (option.withCredentials && 'withCredentials' in xhr) {
				xhr.withCredentials = true;
			}

			var headers = option.headers || {};
			for (var h in headers) {
				if (headers.hasOwnProperty(h)) {
					xhr.setRequestHeader(h, headers[h]);
				}
			}
			send(xhr,formData);
			// xhr.send(formData);
			// xhr.sendAsBinary(formData);
		}
        upload({
            action: action,
            filename: name,
            file: {name:"userfile"},
            bin: decodeData,
            multipart: multipart,
            headers: headers,
            onProgress: function onProgress(e) {
                // console.log("progressing",e, dataUrl);
				_this3.setState({"percent":Math.floor(e.percent)});
				_this3.props.onUploadProgress(e);
            },
            onSuccess: function onSuccess(res) {
                if (formatter) {
                    res = formatter(res);
                }
                //console.log("success",res, dataUrl);
				if(res.code==200){
					_this3.props.onUploadSuccess(res);
				}else{
					// Dialog.alert({content:"抱歉，上传出错，"+res.sub_code});
					_this3.props.onUploadError("上传出错", res);
				}
                _this3.props.onCropClose();
            },
            onError: function onError(err, res) {
				_this3.props.onUploadError(err, res);
                // console.log("erring",err, res, dataUrl);
            }
        });
    };
	render() {
		const previewList = this.props.previewList.map((pre,key)=>{
			let p = pre.split("x");
			return <div key={key} className="crop_preview" style={{"width":p[0]+"px","height":p[1]+"px","overflow": "hidden","marginBottom":"5px"}} />
		});
		return (
			<Dialog visible = {this.props.showCropDialog}
				shouldUpdatePosition = {true}
				onOk = {this.onCropOkay}
				onCancel = {this.props.onCropCancel}
				onClose = {this.props.onCropClose} 
				style = {this.props.dialogStyle}
				title = "请裁切并上传图片，使用鼠标滚轮缩放图片"
				minMargin = {40}>
				<Row className="demo-row">
					<Col fixedSpan="30">
						{/*this.state.loadding*/}
						<CropperJS
							ref='cropper'
							src={this.props.cropPreviewPic}
							style={this.props.copperStyle}
							preview=".crop_preview"
							viewMode={2}
							// Cropper.js options
							aspectRatio={this.props.aspectRatio}
							guides={true}
							cropend={this.cropDone}
							build={()=>{console.log("cropper is installing");}}
							built={()=>{this.hideLoading();console.log("done")}}
							/>
					</Col>
					<Col fixedSpan="17">
						{previewList}
					</Col>
				</Row>
				<Row>
					<Progress percent={this.state.percent} type="progressive" />
				</Row>
				<div style={{clear:"both"}}></div>
			</Dialog>
		);
	}
}
